import datetime
import time
from nonebot.adapters.cqhttp import Bot
from nonebot.adapters.cqhttp.event import Event
from nonebot.permission import SUPERUSER

from nonebot.plugin import on_command
from nonebot.rule import to_me
from nonebot.typing import T_State

from ...dao import group_dao, assignment_dao, class_student_dao, submit_record_dao
from ...model.assignment import Assignment
from ...utils.singleton import SingletonMeta
from ...utils.utils import get_options_list


class GroupAttendDict(metaclass=SingletonMeta):
    def __init__(self):
        self.attend = {}


launch_attendance = on_command("发起签到", rule=to_me(), permission=SUPERUSER)


@launch_attendance.handle()
async def launch_attendance_handle(bot: Bot, event: Event, state: T_State):
    cls_list = await group_dao.getAllClass(bot)
    cls_options = get_options_list(list(map(lambda x: x.name, cls_list)))
    state["cls_list"] = cls_list
    state["class_count"] = len(cls_list)
    await launch_attendance.send(cls_options)


@launch_attendance.got("class_no", prompt="你想在哪个班发起签到呢？")
async def handle_class(bot: Bot, event: Event, state: T_State):
    try:
        num = int(state["class_no"])
    except ValueError:
        await launch_attendance.reject("请输入数字！")

    if num < 0 or state["class_count"] <= num:
        await launch_attendance.reject("请输入在{}到{}之间的数字！".format(0, state["class_count"] - 1))

    # get target group_id
    cls_list = state["cls_list"]
    cls_gids = list(map(lambda x: x.gid, cls_list))
    target_gid = cls_gids[num]

    # turn target_id into is_in_attendence state and set a "timer"
    GroupAttendDict().attend[str(target_gid)] = int(round((time.time()) * 1000))

    # insert the attendence into DB(Assignment)
    attendance = Assignment.attendence(target_gid)
    await assignment_dao.insert_assignment(attendance)
    # insert the defalut submit_record into DB(Submit_Record)
    assignmentID = await assignment_dao.get_assignment_id(target_gid, str(datetime.date.today()))
    studentID_list = await class_student_dao.get_class_student_list(target_gid)
    await submit_record_dao.insert_record(assignmentID[0], studentID_list)
    
    await launch_attendance.send("签到发起成功")
